package com.atguigu.dao.impl;

import com.atguigu.bean.User;
import com.atguigu.dao.UserDao;
import noframework.atguigu.utils.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * projectName: javaweb
 *
 * @author: 赵伟风
 * time: 2022/7/2 14:20 周六
 * description: 用户数据库访问实现类
 */
public class UserDaoImpl implements UserDao {


    /**
     * 根据账号和密码查询数据库用户存在的数量
     *
     * @param username 账号
     * @param password 密码 密文
     * @return 返回存在的数量
     */
    @Override
    public Long queryUser(String username, String password) {

        //4. 数据库的curd
        String sql = "select count(1) ct from user where u_account = ? and u_password = ? ; ";

        QueryRunner queryRunner = new QueryRunner(JDBCUtil.getDataSource());
        Long count = 0L;
        try {
            count = (Long) queryRunner.query(sql, new ScalarHandler(), username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return count;
    }

    /**
     * 查询所有用户信息
     *
     * @return 用户信息集合
     */
    @Override
    public List<User> queryAll() {
        //数据库curd
        QueryRunner queryRunner = new QueryRunner(JDBCUtil.getDataSource());

        //编写sql语句
        //TODO: 列名必须等于实体的属性名，才会自动映射到实体类对象！ 列名不等于，可以起别名！
        //      列名 as 别名 ， 列名 别名
        String sql = "select u_id uId , u_account uAccount,u_password uPassword,u_name uName ," +
                " u_sex uSex,u_age uAge , u_tel uTel,u_type uType from user;";


        List<User> userList = null;
        try {
            userList = queryRunner.query(sql, new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return userList;
    }


}
